package com.hnkywl.sts.webservice.bg.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.bg.BgWzbmService;
import com.hnkywl.sts.webservice.bg.IGoodsCode;
import com.hnkywl.sts.webservice.bg.util.StackTraceUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-5-21
 * Time: 下午9:15
 * To change this template use File | Settings | File Templates.
 */
@Service
public class GoodsCodeService implements IGoodsCode, ApplicationContextAware {
    private ApplicationContext applicationContext;
    // 保供物资编码service
    private BgWzbmService bgWzbmService;
    private WebserviceLogService webserviceLogService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        bgWzbmService = (BgWzbmService) applicationContext.getBean("bgWzbmService");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }

    public String dogoodscode(String goodsCodeXML) {
        // 返回值
        List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
        Map<String,Object> res = new HashMap<String, Object>();
        String exception = "";
        Gson gson = new Gson();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = gson.fromJson(goodsCodeXML, new TypeToken<ArrayList<Map<String, Object>>>() {}.getType());
        if (null == list || list.size() <= 0) {
            res.put("code","1");
            res.put("msg", "缺失参数或者参数为空！");
            resList.add(res);
        } else {
            // 进行数据处理，调用service里的方法
            try {
                resList = this.bgWzbmService.interfaceSave(list);
                res.put("code", "0");
                res.put("msg", "创建物资已成功！");
            } catch (Exception e) {
                e.printStackTrace();
                exception = StackTraceUtil.getStackTrace(e);
                res.put("code", "1");
                res.put("msg", e.getMessage());
            }
            resList.add(res);
        }
        webserviceLogService.saveServerLog(
                GoodsCodeService.class.getName(),
                "dogoodscode",
                goodsCodeXML,
                "返回代码：" + res.get("code") + "  说明：" + res.get("msg"),
                exception,
                ""
        );
        return new Gson().toJson(resList);
    }

     /**
     * 解析xml转化为list
     *
     * @param goodsCodeXML
     * @return
     */
    /*private List<BgWzbm> getGoodsCodes(String goodsCodeXML) {
        List<BgWzbm> list = new ArrayList<BgWzbm>();
        BgWzbm bgWzbm;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = factory.newDocumentBuilder();
            String encoded = "utf-8";
            if (goodsCodeXML.indexOf("gb2312") != -1) {
                encoded = "gb2312";
            }
            Document doc = builder.parse(new ByteArrayInputStream(goodsCodeXML.getBytes(encoded)));
            int nodeLength = doc.getElementsByTagName("goodscode").getLength();
            for (int i = 0; i < nodeLength; i++) {
                bgWzbm = new BgWzbm();
                String grade = doc.getElementsByTagName("grade").item(i).getFirstChild().getNodeValue();
                String codeId = doc.getElementsByTagName("codeid").item(i).getFirstChild().getNodeValue();
                String code = doc.getElementsByTagName("code").item(i).getFirstChild().getNodeValue();
//                System.out.println(i + code);
                String name = doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
                String czsj = doc.getElementsByTagName("czsj").item(i).getFirstChild().getNodeValue();
                Node shortName = doc.getElementsByTagName("shortname").item(i).getFirstChild();
                if (null != shortName) {
                    bgWzbm.setShortname(shortName.getNodeValue());
                }
                Node spec = doc.getElementsByTagName("spec").item(i).getFirstChild();
                // grade为4，不能为空
                if (grade.equals("4") && null != spec) {
                    bgWzbm.setSpec(spec.getNodeValue());
                }
                Node material = doc.getElementsByTagName("material").item(i).getFirstChild();
                if (null != material) {
                    bgWzbm.setMaterial(material.getNodeValue());
                }
                Node unit = doc.getElementsByTagName("unit").item(i).getFirstChild();
                if (null != unit) {
                    bgWzbm.setUnit(unit.getNodeValue());
                }
                Node provider = doc.getElementsByTagName("provider").item(i).getFirstChild();
                if (null != provider) {
                    bgWzbm.setProvider(provider.getNodeValue());
                }
                Node parentCode = doc.getElementsByTagName("parentcode").item(i).getFirstChild();
                // 如果grade为2,3,4时，不能为空
                if (grade.equals("2") || grade.equals("3") || grade.equals("4")) {
                    bgWzbm.setParentcode(parentCode.getNodeValue());
                }
                Node picNo = doc.getElementsByTagName("picno").item(i).getFirstChild();
                if (null != picNo) {
                    bgWzbm.setPicno(picNo.getNodeValue());
                }
                String opt = doc.getElementsByTagName("opt").item(i).getFirstChild().getNodeValue();
                bgWzbm.setGrade(Integer.valueOf(grade));
                bgWzbm.setCodeid(codeId);
                bgWzbm.setCode(code);
                bgWzbm.setName(name);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date toDate = dateFormat.parse(czsj);
                bgWzbm.setCzsj(toDate);
                bgWzbm.setOpt(Integer.valueOf(opt));
                // 判断数字是否合法
                if (isIllegal(Integer.valueOf(grade), Integer.valueOf(opt))) {
                    throw new Exception();
                }
                list.add(bgWzbm);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }*/


    /**
     * 判断数据是否非法
     *
     * @param grade
     * @param opt
     * @return
     */
    private boolean isIllegal(int grade, int opt) {
        // 判断type值是否正确
        if (grade != 1 && grade != 2 && grade != 3 && grade != 4) {
            return true;
        }
        // 判断opt值是否正确
        if (opt != 0 & opt != 1 && opt != 2 && opt != 3) {
            return true;
        }
        return false;
    }
}